package application;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * A Servlet that handles search requests
 * @author Ben
 */
public class SearchServlet extends HttpServlet {
        
        /**
         * The constructor for the Servlet
         */
        public SearchServlet() {
        super();
    }

	/**
	 * method called for GET action
         * 
         * @param request 
         * @param response 
         * @throws ServletException
         * @throws IOException  
         */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * Takes in and processes request from search.jsp's form
         * 
         * @param request 
         * @param response
         * @throws ServletException
         * @throws IOException  
         */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try
		{
                    HttpSession session = request.getSession(true);
                    if(session.getAttribute("currentSessionUser") == null)
                        response.sendRedirect("index.jsp?redirect=true");
                    else{
                    String hardiness = request.getParameter("hardiness");
                    String scientificName = request.getParameter("scientificName");
                    
                    if((scientificName==null || scientificName.equals("")) && hardiness.equals("blank")){
                        response.sendRedirect("search.jsp");
                    }
                    if((scientificName==null || scientificName.equals("")) && !hardiness.equals("blank")){
                        response.sendRedirect("search.jsp?hardiness="+hardiness);
                    }
                    if(hardiness.equals("blank")  && !(scientificName==null || scientificName.equals(""))){
                        response.sendRedirect("search.jsp?scientificName="+scientificName);
                    }
                    if(!hardiness.equals("blank") && !(scientificName==null || scientificName.equals(""))){
                        response.sendRedirect("search.jsp?scientificName="+scientificName+"&hardiness="+hardiness);
                    }
                    }
		} catch (Throwable exc)
		{ 
			System.out.println(exc);
		}
	}

}
